package com.eportal.api;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.eportal.entity.TLocksEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.util.CharsetUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.eportal.domain.AppStore;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TLock;
import com.eportal.domain.TMirrorAgent;
import com.eportal.domain.TShelves;
import com.eportal.domain.TStrategy;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.impl.TShelvesServiceImpl;
import com.eportal.util.Config;
import com.eportal.util.DateUtils;
import com.eportal.util.HttpHelper;

public class MdOpenApi {

	private static Logger log = Logger.getLogger(MdOpenApi.class);
	/**
	 * @Description: 添加合作方信息到开发平台
	 * *号为重要必填
	 * @param email *邮件
	 * @param liaisonper *联系人
	 * @param telephone *联系电话
	 * @param agtname *联系人姓名
	 * @param agtaddress 详细地址
	 * @param location 行政区号
	 * @throws Exception
	 */
	public static MdOpenAddAgentJson  addAgent(TAgent tAgent, String platAgtcode, String PlatAppKey) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("email", tAgent.getAgtCode()+"@hzblzx.com");
		map.put("liaisonper", tAgent.getAgtContact());
		map.put("telephone", tAgent.getAgtTel());
		map.put("agtname", tAgent.getAgtName());
		map.put("agtaddress",tAgent.getAddress());
		map.put("location", tAgent.getAreaCode());
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_ADD_AGENT);
		log.info( Config.MD_OPEN_ADD_AGENT+"resp="+resp);
		MdOpenAddAgentJson json = MdOpenAddAgentJson.parse(resp);
		return json;
	}

	/**
	 * 新增社区
	 * *号为重要必填
	 * @param PlatAppKey
	 * @param platAgtcode
	 * @param depart_name * 社区名称
     * @param city_code * 社区所在地，xx省xx市xx区
	 * @param linker 联系人
	 * @param depart_tel 联系电话
	 * @param depart_mail 邮箱
	 * @param street 街道/村/门牌号
	 * @param address通讯地址
	 * @param common 说明
	 * @throws Exception
	 */
	public static MdOpenAddCommunityJson  addCommunity(TCommunity tCommunity, String platAgtcode, String PlatAppKey) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("depart_name", tCommunity.getCommunityName());
		map.put("linker", tCommunity.getLinker());
		map.put("depart_tel", tCommunity.getDepartTel());
		map.put("depart_mail", tCommunity.getDepartMail());
		map.put("city_code",tCommunity.getCityCode());
		map.put("street", tCommunity.getStreet());
		map.put("address", tCommunity.getAddress());
		map.put("common", tCommunity.getComm());
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_ADD_COMMUNITY);
		MdOpenAddCommunityJson json = MdOpenAddCommunityJson.parse(resp);
		return json;
	}


	/**
	 * 安装设备
	 * *号为重要必填
	 * @param departid
	 * @param pid *
	 * @param departid * 安装组织机构编号 addCommunity有返回
	 * @param install_lock_name * 安装钥匙名称
	 * @param install_address  安装具体位置
	 * @param install_gps 安装地理坐标
	 * @param install_work  安装人
	 * @param install_telete 安装人联系电话
	 * @param intall_comm 安装说明
	 * @return
	 * @throws Exception
	 */
	public static MdOpenBaseJson  installLock(TLock entity, String platAgtcode, String PlatAppKey, String departid) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("pid", entity.getPid());
		map.put("departid", departid);
		map.put("install_lock_name", entity.getInstallLockName());
		map.put("install_address", entity.getInstallAddress());
		map.put("install_gps",entity.getInstallGps() );
		map.put("install_work", entity.getInstallWork());
		map.put("install_telete", entity.getInstallTelete());
		map.put("intall_comm", entity.getIntallComm());
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_INSTALL_LOCK);
		log.info(Config.MD_OPEN_INSTALL_LOCK +",resp="+resp);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	/**
	 * 安装设备
	 * *号为重要必填
	 * @param departid
	 * @param pid *
	 * @param departid * 安装组织机构编号 addCommunity有返回
	 * @param install_lock_name * 安装钥匙名称
	 * @param install_address  安装具体位置
	 * @param install_gps 安装地理坐标
	 * @param install_work  安装人
	 * @param install_telete 安装人联系电话
	 * @param intall_comm 安装说明
	 * @return
	 * @throws Exception
	 */
	public static MdOpenBaseJson  installLock(TLocksEntity entity, String platAgtcode, String PlatAppKey, String departid) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("pid", entity.getPid());
		map.put("departid", departid);
		map.put("install_lock_name", entity.getInstallLockName());
		map.put("install_address", entity.getInstallAddress());
		map.put("install_gps",entity.getInstallGps() );
		map.put("install_work", entity.getInstallWork());
		map.put("install_telete", entity.getInstallTelete());
		map.put("intall_comm", entity.getIntallComm());
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_INSTALL_LOCK);
		log.info(Config.MD_OPEN_INSTALL_LOCK +",resp="+resp);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	public static MdOpenBaseJson  changeTlockAgt(String pids, String agtCode, String platAgtcode, String PlatAppKey) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("pids", pids);
		map.put("targetAgtcode", agtCode);
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_CHANGE_LOCK);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	/**
	 * 生成钥匙
	 * @param pid
	 * @param user_id 用户手机号
	 * @param validity 钥匙有效期 格式：yyyyMMdd 20161109
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object>  qeyKeys(String pid,String platAgtcode, String PlatAppKey,String user_id,String validity) throws Exception{
		Map<String, Object> result = null;
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("agt_num", platAgtcode);
			map.put("app_key", PlatAppKey);
			map.put("pid", pid);
			map.put("user_id", user_id);
			map.put("validity", validity);
			String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_QRY_KEYS);
			log.info(resp);
			result = MdOpenQryKeysJson.parseList(resp);
		} catch (Exception e) {
			throw new Exception(e);
		}
		return result;
	}

	public static MdOpenAddTShelvesJson  addTShelves(TShelves tShelves, String platAgtcode, String PlatAppKey) throws Exception{
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("agt_num", platAgtcode);
//		map.put("app_key", PlatAppKey);
//		map.put("name", tShelves.getName());
//		map.put("type", tShelves.getType());
//		map.put("visiable", tShelves.getVisiAble()+"");
//		map.put("isshare", "1");
//		map.put("isonline",tShelves.getIsOnLine()+"");
//		map.put("content", tShelves.getContent());
//		map.put("curl", tShelves.getcUrl());

		MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
		//---------必填

		reqEntity.addPart("agt_num", new StringBody(platAgtcode));
		reqEntity.addPart("app_key", new StringBody(PlatAppKey));

		reqEntity.addPart("name", new StringBody(tShelves.getName(),Charset.forName("UTF-8")));
		// 类型,文字T,图片I多媒体M
		reqEntity.addPart("type", new StringBody(tShelves.getType()));
		//是否会自动隐藏，0：不自动隐藏，1：自动隐藏
		reqEntity.addPart("visiable", new StringBody(tShelves.getVisiAble()+""));
		// 共享标记,默认0,1的话,允许其他代理商的用户可见目前平台发布的都是1'
		reqEntity.addPart("isshare", new StringBody("1"));
		// 上下架,0,下架默认1
		reqEntity.addPart("isonline", new StringBody(tShelves.getIsOnLine()+""));
		reqEntity.addPart("content", new StringBody(tShelves.getContent()));//type=T时填写显示内容,type=其他时,为附件的路径,可随意填
		//------选填
		String destDir = ServletActionContext.getRequest().getServletContext().getRealPath("/");

		FileBody fileBody = new FileBody(new File(destDir+tShelves.getContent()));
		reqEntity.addPart("upload", fileBody);//资源文件
		StringBuffer url = new StringBuffer(Config.MD_OPEN_TSHELVES_URL);
		url.append("/redEnvelope/index.do?resource_id=");
		url.append(tShelves.getSid());
		url.append("&url=");
		url.append(URLEncoder.encode(tShelves.getcUrl()));

		reqEntity.addPart("curl", new StringBody(url.toString()));//跳转链接

		String resp = HttpHelper.doPost(Config.MD_OPEN_TSHELVES_ADD, reqEntity.setCharset(CharsetUtils.get("UTF-8")).build());
		MdOpenAddTShelvesJson json = MdOpenAddTShelvesJson.parse(resp);
		return json;
	}

	public static MdOpenBaseJson  editTShelves(TShelves tShelves, String platAgtcode, String PlatAppKey, boolean ifUpload) throws Exception{
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("agt_num", platAgtcode);
//		map.put("app_key", PlatAppKey);
//		map.put("name", tShelves.getName());
//		map.put("type", tShelves.getType());
//		map.put("visiable", tShelves.getVisiAble()+"");
//		map.put("isshare", "1");
//		if (tShelves.getIsOnLine() == 2) {
//			map.put("isonline","0");
//		}else{
//			map.put("isonline",tShelves.getIsOnLine()+"");
//		}
//		map.put("content", tShelves.getContent());
//		map.put("sid", tShelves.getOpenSid());
//		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_TSHELVES_ADD);
		MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
		//---------必填
		reqEntity.addPart("agt_num", new StringBody(platAgtcode));
		reqEntity.addPart("app_key", new StringBody(PlatAppKey));
		reqEntity.addPart("sid", new StringBody(tShelves.getOpenSid()));
		reqEntity.addPart("name", new StringBody(tShelves.getName(),Charset.forName("UTF-8")));
		// 类型,文字T,图片I多媒体M
		reqEntity.addPart("type", new StringBody(tShelves.getType()));
		//是否会自动隐藏，0：不自动隐藏，1：自动隐藏
		reqEntity.addPart("visiable", new StringBody(tShelves.getVisiAble()+""));
		// 共享标记,默认0,1的话,允许其他代理商的用户可见目前平台发布的都是1'
		reqEntity.addPart("isshare", new StringBody("1"));
		// 上下架,0,下架默认1
		if (tShelves.getIsOnLine() == 2) {
			reqEntity.addPart("isonline", new StringBody("0"));
		}else{
			reqEntity.addPart("isonline", new StringBody(tShelves.getIsOnLine()+""));
		}
		reqEntity.addPart("content", new StringBody(tShelves.getContent()));//type=T时填写显示内容,type=其他时,为附件的路径,可随意填
		if (ifUpload) {
			String destDir = ServletActionContext.getRequest().getServletContext().getRealPath("/");
			FileBody fileBody = new FileBody(new File(destDir+tShelves.getContent()));
			reqEntity.addPart("upload", fileBody);//资源文件
		}
		StringBuffer url = new StringBuffer(Config.MD_OPEN_TSHELVES_URL);
		url.append("/redEnvelope/index.do?resource_id=");
		url.append(tShelves.getSid());
		url.append("&url=");
		url.append(URLEncoder.encode(tShelves.getcUrl()));
		reqEntity.addPart("curl", new StringBody(url.toString()));//跳转链接
		String resp = HttpHelper.doPost(Config.MD_OPEN_TSHELVES_EDIT, reqEntity.setCharset(CharsetUtils.get("UTF-8")).build());
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	public static MdOpenAddTShelvesJson  addTStrategy(String openSid, String comuPlatDepartId, String agtPlatDepartId, TStrategy tStrategy, String platAgtcode, String PlatAppKey) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("gid", openSid);
		map.put("priority", tStrategy.getPriority()+"");
		map.put("community", comuPlatDepartId);
		map.put("acceptAgtcode", agtPlatDepartId);
		map.put("timefrom", DateUtils.dateFormat.format(tStrategy.getTimeFrom()));
		map.put("timeto",DateUtils.dateFormat.format(tStrategy.getTimeTo()));
		map.put("showtime", tStrategy.getShowTime());
		map.put("expiredtime", tStrategy.getExpiredTime());
		map.put("enabledflag", tStrategy.getEnabledflag()+"");
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_TSTRATEGY_ADD);
		MdOpenAddTShelvesJson json = MdOpenAddTShelvesJson.parse(resp);
		return json;
	}

	public static MdOpenBaseJson  editTStrategy(String openSid, String comuPlatDepartId, String agtPlatDepartId, TStrategy tStrategy, String platAgtcode, String PlatAppKey) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("sid", openSid);
		map.put("priority", tStrategy.getPriority()+"");
		map.put("community", comuPlatDepartId);
		map.put("acceptAgtcode", agtPlatDepartId);
		map.put("timefrom", DateUtils.dateFormat.format(tStrategy.getTimeFrom()));
		map.put("timeto",DateUtils.dateFormat.format(tStrategy.getTimeTo()));
		map.put("showtime", tStrategy.getShowTime());
		map.put("expiredtime", tStrategy.getExpiredTime());
		map.put("enabledflag", tStrategy.getEnabledflag()+"");
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_TSTRATEGY_EDIT);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	/**
	 * 推送消息
	 * @param userid 推送的用户id
	 * @param communityid 推送的社区id
	 * @param targetObj 推送对象 选项：user:用户，community:社区
	 * @param type 消息类型：key_1:有新的钥匙，msg_2:有新的社区消息
	 * @return
	 * @throws Exception
	 */
	public static MdOpenBaseJson  sendMsg(String userid,String communityid,String targetObj,String type) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		map.put("userid", userid);
		map.put("communityid", communityid);
		map.put("targetObj", targetObj);
		map.put("type", type);
		String resp = HttpHelper.doPostForm(map, Config.MD_SEND_MSG);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}

	/**
	 * 微信公众号
	 * @param tMirrorAgent
	 * @param string
	 * @param string2
	 * @return
	 * @throws Exception
	 */
	public static MdOpenBaseJson addWeChatSubscription(TMirrorAgent tMirrorAgent, String platAgtcode, String PlatAppKey) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("agt_num", platAgtcode);
		map.put("app_key", PlatAppKey);
		map.put("gid", tMirrorAgent.getGid());
		map.put("app_id", tMirrorAgent.getWxAppId());
		map.put("app_secret", tMirrorAgent.getWxAppSecret());
		map.put("service_token", tMirrorAgent.getGroupToken());
		map.put("service_encoding_key", tMirrorAgent.getEncodingAesKey());
		map.put("company_name","");
		map.put("cname", tMirrorAgent.getcName());
		map.put("product_id", tMirrorAgent.getProductId());
		String resp = HttpHelper.doPostForm(map, Config.MD_OPEN_WeChat);
		MdOpenBaseJson json = MdOpenBaseJson.parse(resp);
		return json;
	}
}
